<?php

namespace App\Models\Traits;

use App\Models\Vote;

trait VoteTrait
{
    // 点赞 或者 踩
    public function vote($user, $type)
    {
        $attributes = [
            'user_id' => $user->id,
        ];

        if (! $this->votes($type)->where($attributes)->exists()) {
            $this->votes($type)->create([
                'user_id' => $user->id,
                'type' => $type,
            ]);
        }
    }

    // 取消点赞
    public function cancelVoteUp($user)
    {
        $this->cancelVote($user, 'vote_up');
    }

    //  取消 踩
    public function cancelVoteDown($user)
    {
        return $this->cancelVote($user, 'vote_down');
    }

    public function cancelVote($user, $type)
    {
        $attributes = [
            'user_id' => $user->id,
        ];

        return $this->votes($type)->where($attributes)->delete();
    }


    public function votes($type)
    {
        return $this->morphMany(Vote::class, 'voted')->whereType($type);
    }

    public function voteUp($user)
    {
        return $this->vote($user, 'vote_up');
    }

    public function voteDown($user)
    {
        $this->vote($user, 'vote_down');
    }

    // 是否已经点赞
    public function isVotedUp($user)
    {
        return $this->isVoted($user, 'vote_up');
    }

    // 判断是否 踩过
    public function isVotedDown($user)
    {
        return $this->isVoted($user, 'vote_down');
    }

    public function isVoted($user, $type)
    {
        if (! $user) {
            return false;
        }

        return (bool) $this->votes($type)->where('user_id', $user->id)->count();
    }

    // 获取已点赞数量
    public function getUpVotesCountAttribute()
    {
        return $this->votes('vote_up')->count();
    }

    // 获取 踩 的数量
    public function getDownVotesCountAttribute()
    {
        return $this->votes('vote_down')->count();
    }
}
